<?php

namespace app\aiv110\controller;

use app\aiv110\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\aiv110\model\Item;
use app\aiv110\model\ItemToGoods;
use app\aiv110\model\ItemProcess;
use app\aiv110\model\ItemClass;
use think\db\Expression;
use app\aiv110\model\CtmCollect;
use app\aiv110\model\Comment;
use app\aiv110\model\Custom;
use think\Request;

class ItemController extends CommonController {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 90000  
         * 90001  
         * 90002  
         * 90003  
         * 90004  
         * 90004
         */
    }

    /*
     * 项目详情
     * author xfwed 
     * date 2020.09.24
     * 
     * @param int id 项目id 必须
     * @param int Ctm_id 用户id  非必须
     */

    public function itemInfo() {
        $rule = [
            'id' => 'require|integer',
        ];
        $msg = [
            'id.require' => '项目id必须',
            'id.integer' => '项目id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        $id = $all['id'];
        $where['id'] = $all['id'];
        //护理产品
        $itemGoods = ItemToGoods::alias('itg')
                ->join(['goods_info'=>'g'],'g.id = itg.goods_info_id','left')
                ->join(['goods_images'=>'gi'],'itg.goods_info_id = gi.goods_id','left')
                ->where('itg.item_id',$id)
                ->where('gi.type',2)
                ->field('g.id,g.name,g.icon,g.summary,gi.images')
                ->select();
        //适用人群
        $people = Item::where('id',$id)->value('people');
        //服务流程
        $itemProcess = ItemProcess::alias('p')
                ->join(['goods_info'=>'g'],'g.id = p.good_id','left')
                ->join(['goods_images'=>'gi'],'p.good_id = gi.goods_id and gi.type = 2','left')
                ->where('p.item_id',$id)
                ->where('p.is_del',2)
                ->order('p.sort asc')
                ->field('p.name,p.minute,p.facility,p.facility_img,p.good_id,p.content,p.img,g.icon,g.name goodname,g.summary,gi.images')
                ->select();
        $data['itemGoods'] = $itemGoods;
        $data['people'] = $people;
        $data['itemProcess'] = $itemProcess;
        return Utils::ajaxReturn(0, '查询成功', $data);
    }
    
    /*
     * 医美项目列表
     * author xfwed 
     * date 2020.09.25
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function yimeiItemList() {
        $all = input('param.');
        
        $where['is_del'] = 1;
        $where['status'] = 2;
        $where['is_yimei'] = 1;
        $list = Item::where($where)
                ->field('id,item_name,vice_name,item_price,item_img,is_yimei,sell_count')
                ->order('sell_count desc id desc')
                ->select();

        return Utils::ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 小程序首页金刚区进入
     * author xfwed 
     * date 2020.11.26
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function fastItemList() {
        $rule = [
            'type' => 'require|integer',
            'item_class' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'type.require' => '分类必须',
            'type.integer' => '分类为数字',
            'item_class.require' => '项目分类必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        
        $type = $all['type'];//美容护理 2美体塑形 3丽人专享
        $itemClass = $all['item_class'];
        $search = input('param.search');
        $version = input('param.version');//小程序版本号
        
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;//->limit($offset, $perPage)
        if($type == 1){
            $where['is_yimei'] = 2;
            if($itemClass == 0){//美容护理  全部
                $where['item_type'] = ['in','3,5,4,7'];//3补水保湿 5抗衰紧致 4美白焕颜 7问题肌肤
            }  else {
                $where['item_type'] = $itemClass;
            }
            //查询图标
            $iconList = ItemClass::where('type',0)
                    ->where('id','in','3,5,4,7')
                    ->field('id,name,icon')
                    ->orderRaw("id=3 desc,id=5 desc,id=4 desc,id=7 desc")
                    ->select();
            $iconList[4]['id'] = 0;
            $iconList[4]['name'] = '全部';
            $iconList[4]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/admin/20201130/all.png';
        }elseif ($type == 2) {
            $where['is_yimei'] = 2;
            if($itemClass == 0){//美容护理  全部
                $where['item_type'] = ['in','10,12,11,13,15,9,14'];//10胸部护理 12臀部护理 11肩颈调理 13腰腹护理 15经络淋巴 9颈部护理 14瘦身塑形
            }  else {
                $where['item_type'] = $itemClass;
            }
            $iconList = ItemClass::where('type',0)
                    ->where('id','in','10,12,11,13,15,9,14')
                    ->field('id,name,icon')
                    ->orderRaw("id=10 desc,id=12 desc,id=11 desc,id=13 desc,id=15 desc,id=9 desc,id=14 desc")
                    ->select();
            $iconList[7]['id'] = 0;
            $iconList[7]['name'] = '全部';
            $iconList[7]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/admin/20201130/all.png';
            //print_r(ItemClass::getLastSql());
        }elseif ($type == 3) {
            $where['is_yimei'] = 1;
            //$iconList = [['img'=>'http://47.104.83.107/images/kkmimg/kkmai/admin/20201130/yimei.png']];//医美轮播图
            $iconList[0]['id'] = 0;
            $iconList[0]['name'] = '全部';
            $iconList[0]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/all.png';
            $iconList[1]['id'] = 1;
            $iconList[1]['name'] = '热玛吉';
            $iconList[1]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/rmj.png';
            $iconList[2]['id'] = 3;
            $iconList[2]['name'] = '伊丽丝白';
            $iconList[2]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/ylsb.png';
            $iconList[3]['id'] = 4;
            $iconList[3]['name'] = '华晟奥源';
            $iconList[3]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/hsoy.png';
            
            $itemType = input('param.itemType');//0全部 1热玛吉 3伊丽丝白 4华晟奥源
            if($itemType){
                $where['type'] = $itemType;
            }
        }
        if($search){
            $where['item_name'] = ['like','%'.$search.'%'];
        }
        $where['is_del'] = 1;
        $where['status'] = 2;
        //查询小程序审核隐藏的项目
        if($version){
            $item_ids = Db::name('xcx_audit')
                    ->where('version',$version)
                    ->where('is_open',1)
                    ->value('item_ids');
            if($item_ids){
                $where['id'] = ['not in',$item_ids];
            }
        }
        
        $list = Item::where($where)
                ->field('id,item_name,item_price,special_money,item_img,sell_count_base+sell_count sell_count,activityDesc')
                ->limit($offset, $perPage)
                ->select();
        foreach ($list as $k => $v){
            $list[$k]['collectNum'] = CtmCollect::where('pro_id',$v['id'])
                    ->where('type',1)
                    ->count();
            $commentRow = Comment::alias('p')
                    ->join('custom c','c.id = p.ctm_id','left')
                    ->where('p.item_id',$v['id'])
                    ->where('p.item_star',5)
                    ->where('p.item_content','<>','')
                    ->field('p.item_content,c.custom_photo')
                    ->find();
            $list[$k]['commentImg'] = $commentRow['custom_photo'];
            $list[$k]['commentContent'] = $commentRow['item_content'];
        }
        $data['iconList'] = $iconList;
        $data['itemList'] = $list;
                

        return Utils::ajaxReturn(0, '查询成功', $data);
    }
    
    /*
     * 新年活动-i美套餐列表
     * author xfwed 
     * date 2021.1.27
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function newYearItemList() {
        $rule = [
            'ctm_id' => 'require|integer',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'ctm_id.integer' => '用户id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        
        $ctm_id = $all['ctm_id'];//美容护理 2美体塑形 3丽人专享
        $vip_status = Custom::where('id',$ctm_id)->value('vip_status');
        if($vip_status == 2){
            $p = 10;
        } else {
            $p = 20;
        }
        $list = Item::where('is_del',1)
                ->where('status',2)
                ->where('is_imeigroup',1)
                ->field('id,item_name,item_price,special_money,item_img')
                ->order('sort desc')
                ->select();
        foreach ($list as $k => $v){
            $itemNum = Db::name('imeigroup')->where('item_id',$v['id'])
                    ->where('is_del',2)
                    ->count();
            $list[$k]['itemNum'] = $itemNum;
            $list[$k]['jianPrice'] = $itemNum*$p;
        }
        return Utils::ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 拍照测肤推荐项目
     * author xfwed 
     * date 2021.10.13
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function tjItemList() {
        $rule = [
            'ctm_id' => 'require|integer',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'ctm_id.integer' => '用户id为数字',
        ];

        $all = input('param.');
        $ctm_id = $all['ctm_id'];
        $cityName = Request::instance()->header('cityname');
        $json = '{"str":"'.$cityName.'"}';
        $arr = json_decode($json,true);
        $a = $arr['str'];
        $json = '{"str":"'.$a.'"}';
        $arr = json_decode($json,true);
        $cityName =  $arr['str'];

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        
        $hetData = Db::name('het_data')
                ->where('ctm_id',$ctm_id)
                ->where('type',1)
//                ->where('id',80)
                ->order('id desc')
                ->field('id,csdata')
                ->find();
        $csdata = $hetData['csdata'];
        $csdata = json_decode($csdata,true);
        //轻度敏感 skinSensitive sensitiveSeq
        //干燥缺水 moistureOverall -- level
        //油脂旺盛 oilOverall level 
        //黑头毛孔 photographSkinBlackhead  blackheadLevelSeq
        //痘痘  acneOverall  level 
        //色素斑 pigmentationOverall  level
        //细纹 wrinkleOverall  level 
        //黑眼圈  mostSeriousDarkCircle  darkCircleSeq
        //眼袋 photographSkinPouch  pouchLevelSeq
        //肤色暗沉  skinDark  level
        $level['kinSensitive'] = isset($csdata['skinSensitive']['sensitiveSeq'])?$csdata['skinSensitive']['sensitiveSeq']:0;
        $level['moistureOverall'] = isset($csdata['moistureOverall']['level'])?$csdata['moistureOverall']['level']:0;
        $level['oilOverall'] = isset($csdata['oilOverall']['level'])?$csdata['oilOverall']['level']:0;
        $level['photographSkinBlackhead'] = isset($csdata['photographSkinBlackhead']['blackheadLevelSeq'])?$csdata['photographSkinBlackhead']['blackheadLevelSeq']:0;
        $level['acneOverall'] = isset($csdata['acneOverall']['level'])?$csdata['acneOverall']['level']:0;
        $level['pigmentationOverall'] = isset($csdata['pigmentationOverall']['level'])?$csdata['pigmentationOverall']['level']:0;
        $level['wrinkleOverall'] = isset($csdata['wrinkleOverall']['level'])?$csdata['wrinkleOverall']['level']:0;
        $level['mostSeriousDarkCircle'] = isset($csdata['mostSeriousDarkCircle']['darkCircleSeq'])?$csdata['mostSeriousDarkCircle']['darkCircleSeq']:0;
        $level['photographSkinPouch'] = isset($csdata['photographSkinPouch']['pouchLevelSeq'])?$csdata['photographSkinPouch']['pouchLevelSeq']:0;
        $level['skinDark'] = isset($csdata['skinDark']['level'])?$csdata['skinDark']['level']:0;
        arsort($level);     
        $level = array_slice($level, 0,3);
//        print_r($level);
        $itemid = '';
        foreach ($level as $k=>$v){
            if($k == 'kinSensitive'){
                $tag = 1;
            }elseif ($k == 'moistureOverall') {
                $tag = 2;
            }elseif ($k == 'oilOverall') {
                $tag = 3;
            }elseif ($k == 'photographSkinBlackhead') {
                $tag = 4;
            }elseif ($k == 'acneOverall') {
                $tag = 5;
            }elseif ($k == 'pigmentationOverall') {
                $tag = 6;
            }elseif ($k == 'wrinkleOverall') {
                $tag = 7;
            }elseif ($k == 'mostSeriousDarkCircle') {
                $tag = 8;
            }elseif ($k == 'photographSkinPouch') {
                $tag = 9;
            }elseif ($k == 'skinDark') {
                $tag = 10;
            }
            $id = Item::where('tag', $tag)
                    ->where('type', 0)
                    ->where('is_del', 1)
                    ->where('status', 2)
                    ->where('is_imeigroup', 2)
                    ->where('is_yimei', 2)
                    ->where('is_imeigroup', 2)
                    ->where('is_special', 2)
                    ->orderRaw('rand()')
                    ->value('id');
            if ($id) {
                $itemid = $itemid . ',' . $id;
            }
        }
        
        $list = Item::where('id','in',$itemid)
                ->where('is_del',1)
                ->where('status',2)
                ->field('id,item_name,vice_name,item_price,special_money,item_img,sell_count+sell_count_base sell_count,tag,people,service_time')
                ->select();
        foreach ($list as $k => $v){
            $itemprocess = ItemProcess::where('item_id',$v['id'])
                    ->where('is_del',2)
                    ->order('sort asc')
                    ->field('sort,name,minute,img')
                    ->select();
            $list[$k]['itemprocess'] = $itemprocess;
        }
        $data['list'] = $list;
        $data['img'] = Db::name('pic')
                ->where('type',17)
                ->where('isshow',1)
                ->where('city_name','in','全国,'.$cityName)
                ->value('pic');
        //查询项目的商品
        $goodsList = Db::name('item_to_goods')
                ->alias('i')
                ->join(['goods_info'=>'g'],'g.id = i.goods_info_id','left')
                ->join(['goods_info_detail'=>'d'],'d.goodsId = g.id','left')
                ->where('i.item_id','in',$itemid)
                ->field('g.id,g.name,g.icon,g.sell_count,g.product_efficacy,g.product_ingredient,d.oriPrice,d.price')
                ->group('g.id')
                ->select();
        $data['goodsList'] = $goodsList;
        return Utils::ajaxReturn(0, '查询成功', $data);
    }

}
